import { useContext } from 'react'
import { PageContext } from '../../store'
import { componentsList } from '../../components'

import { v4 } from 'uuid'

export const Editor = () => {
  const { list, setList, setCurrentConfigId } = useContext(PageContext)

  const handleDragOver = (e) => {
    e.preventDefault()
  }

  const handleDrop = (e) => {
    const droppedElementName = e.dataTransfer.getData('text/plain')
    // console.log(droppedElementName)

    setList(list.concat({
      id: v4(),
      name: droppedElementName,
      props: {},
      children: []
    }))
    // console.log(list)
  }

  const getComponent = (name) => {
    return componentsList.find((item) => item.name === name)
  }

  const handleClickConfig = (id) => {
    setCurrentConfigId(id)
  }


  const renderComponents = () => {
    return list.map(item => {
      const Component = getComponent(item.name).component
      return <span onClick={()=>handleClickConfig(item.id)} key={item.id}>
        <Component {...item.props} />
      </span>
    })
  }

  return (
    <div style={{flex: 1}}>
      <div>设计区</div>
      <div 
        style={{border: '1px dashed #e0e0e0', height: '80vh'}}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
      >
        {renderComponents()}
      </div>
    </div>
  )
}